package com.hxc.controller;

import cn.hutool.jwt.JWT;
import com.hxc.pojo.User;
import com.hxc.service.UserService;
import com.hxc.utils.GitUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("user")
@Controller
public class UserController {
    @Autowired
    UserService userService;
    byte[] key = "1234567890".getBytes();

    @RequestMapping("toLogin")
    public String toLogin(Model model){
        model.addAttribute("user",new User());
        return "login";
    }

    @RequestMapping("login")
    public String login(String username, String password, Model model, HttpServletResponse response){
        User user = userService.getUser(username);
        if (!user.getPassword().equals(password)){
            model.addAttribute("password","密码错误");
            return "login";
        }
        String token = JWT.create()
                .setPayload("username", username)
                .setPayload("uid",user.getUid())
                .setKey(key)
                .sign();
        Cookie cookie = new Cookie("login_token", token);
        cookie.setPath("/");
        //设置cookie存活时长
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);
        return "redirect:/main/list";
    }

    @RequestMapping("auth")
    public String auth(String code,HttpServletResponse response){
        Object username = GitUtils.getGiteeName(code, "http://localhost:80/user/auth");
        User user = userService.getUser(username.toString());
        if (StringUtils.isEmpty(user)){
            userService.addUser(username.toString());
        }
        User user1 = userService.getUser(username.toString());
        String token = JWT.create()
                .setPayload("username", username.toString())
                .setPayload("uid",user1.getUid())
                .setKey(key)
                .sign();
        Cookie cookie = new Cookie("login_token", token);
        cookie.setPath("/");
        //设置cookie存活时长
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);
        return "redirect:/main/list";
    }
}
